﻿import re

import logging
from datetime import datetime

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api.urlfetch import fetch
from google.appengine.api import mail

from views_common import *
import models

import PyRSS2Gen
import smth_iphone_web as smth

# ##########################################################################################################################
# /
def index(request):
    user = getUser()
    logging.info(user.email())
    config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", user).get()
    if config is None:
        config = models.Configuration(user=user,showTitle=True,showHead=True,showPost=True,showRef=True,showSignature=True,showAttachment=True,showThreadNewPage=True,showThreadOriginUrl=True,threads_count=0,boards_count=0,posts_count=0)
        config.put()
        logging.info('new config added')
    
    login_text, login_url = getLoginAndUrl(request)
    
    is_logged_in = False
    if users.get_current_user():
        is_logged_in = True
        
    payload = {'is_logged_in': is_logged_in ,'login_text':login_text, 'login_url':login_url, }
    
    return render('iwebkit/index.html', payload)

# ##########################################################################################################################
# /top10/
def top10(request):
    top10_threads = smth.getTop10ArticlesList()
    payload = {'title': '十大热门话题', 'threads': top10_threads, }
    return render('iwebkit/threads.html', payload)


# ##########################################################################################################################
# /w/boards/
def boards(request):
    xml = '''<?xml version="1.0" encoding="UTF-8"?>
<boards>
    <board board_name="NewExpress" board_id="582" order="1" description="水木特快"></board>
    <board board_name="Love" board_id="73" order="2" description="谈情说爱"></board>
    <board board_name="FamilyLife" board_id="9" order="3" description="家庭生活"></board>
    <board board_name="MyPhoto" board_id="874" order="4" description="个人Show"></board>
    <board board_name="Joke" board_id="63" order="5" description="笑话"></board>
    <board board_name="Apple" board_id="719" order="6" description="苹果"></board>
    <board board_name="NewSoftware" board_id="99" order="7" description="新软"></board>
    <board board_name="ITExpress" board_id="26" order="8" description="IT特快"></board>
    <board board_name="MyWallet" board_id="574" order="9" description="个人理财"></board>
    <board board_name="CreditCard" board_id="1097" order="10" description="信用卡理财"></board>
    <board board_name="Age" board_id="953" order="11" description="大龄男女"></board>
    <board board_name="Movie" board_id="92" order="12" description="电影"></board>
    <board board_name="OMTV" board_id="448" order="13" description="欧美电视"></board>
    <board board_name="RealEstate" board_id="309" order="14" description="房地产论坛"></board>
    <board board_name="RealEstate_review" board_id="1112" order="15" description="房产观澜"></board>
    <board board_name="WorkLife" board_id="383" order="16" description="职业生涯"></board>
    <board board_name="PrisonBreak" board_id="904" order="17" description="越狱"></board>
    <board board_name="GuoJiXue" board_id="540" order="18" description="国计学"></board>
    <board board_name="EconForum" board_id="225" order="19" description="经济论坛"></board>
</boards>'''

    response = HttpResponse(xml)
    response['Content-Type'] = 'text/xml'
    return response

# ##########################################################################################################################
# /w/threads/
def threads(request):
    board_name = request.GET.get('board_name', "NewExpress")
    board_id = int(request.GET.get('board_id', '0'))
    #page_num = 0 means as the last page
    page_num = int(request.GET.get('page_num', '0'))
    
    board_id, threads, page_num_real = smth.getThreadList(board_name, page_num)
    
    xml =  '''<?xml version="1.0" encoding="UTF-8"?>'''
    xml += '''<threads board_name="'''+board_name+'''" board_id="'''+board_id+'''">'''
    for thread in threads:
        #0:thread_id, 1:title, 2:word_count, 3:thread_url
        xml += '''<thread title="'''+thread[1]+'''" thread_id="'''+thread[0]+'''" user="" date=""></thread>'''
    xml += '''</threads>'''

    response = HttpResponse(xml)
    response['Content-Type'] = 'text/xml'
    return response

# ##########################################################################################################################
# /w/posts/
def posts(request):
    board_name = request.GET.get('board_name', "NewExpress")
    board_id = int(request.GET.get('board_id', '0'))
    #page_num = 0 means as the last page
    page_num = int(request.GET.get('page_num', '0'))
    
    logging.info(page_num)
    
    board_id, posts, page_num_real = smth.getPostList(board_name, page_num)
    
    xml =  '''<?xml version="1.0"?>'''
    xml += '''<posts board_name="'''+board_name+'''" page_num="'''+page_num_real+'''" board_id="'''+board_id+'''">'''
    for post in posts:
        #0:post_id, 1:thread_id, 2:author, 3:tag, 4:post_time, 5:title, 6:word_count
        xml += '''<post title="'''+post.title+'''" thread_id="'''+str(post.thread_id)+'''" post_id="'''+str(post.post_id)+'''" user="'''+post.author+'''" date="'''+str(post.post_time)+'''" word_count="'''+str(post.word_count)+'''" tag="'''+post.tag+'''"><![CDATA[]]></post>'''
    xml += '''</posts>'''

    response = HttpResponse(xml)
    response['Content-Type'] = 'text/xml'
    return response
    
    
# ##########################################################################################################################
# /w/post/
def post(request):
    board_name = request.GET.get('board_name', "NewExpress")
    board_id = request.GET.get("board_id", None)
    #thread_id = request.GET.get("thread_id", "0")
    post_id = request.GET.get("post_id", None)
    post_type = request.GET.get("post_type", None)
    
    if board_id == None or board_id=="":
        board_id, posts, page_num_real = smth.getPostList(board_name, 0)
    
    logging.info(post_type)

    if board_id and post_id:
        post_id, thread_id, post_title, postContent = getPostContent(board_id, post_id, post_type)
    
    payload = {'content': postContent, 'board_id': board_id, 'thread_id': thread_id, 'title': post_title, 'post_id': post_id, }
    return render('iwebkit/post.html', payload)
    
    
# ##########################################################################################################################
# get Post Content
def getPostContent(board_id, post_id, post_type):
    
    post_id = smth.getPostId(board_id, post_id, post_type)
    
    post = db.GqlQuery("SELECT * FROM Post WHERE board_id=:1 and post_id=:2", int(board_id), int(post_id)).get()
    
    #logging.info("--------------------------")
    #logging.info(post)
    
    if not post:
        post_id, thread_id, post_title, head, content_text, ref, attachment_html, signature = smth.getPostContent(board_id, post_id)
        #logging.info(post_id)
        
        board_id=int(board_id)
        post_id=int(post_id)
        thread_id=int(thread_id)
        
        head=unicode(head, 'utf-8', 'ignore')
        ref=unicode(ref, 'utf-8', 'ignore')
        attachment_html=unicode(attachment_html, 'utf-8', 'ignore')
        signature=unicode(signature, 'utf-8', 'ignore')
        content_text=unicode(content_text, 'utf-8', 'ignore')
        post_title = unicode(post_title, 'utf-8', 'ignore')
        
        post = models.Post(board_id=board_id, post_id=post_id, thread_id=thread_id, head=head, ref=ref, attachment=attachment_html, signature=signature, content=content_text, title=post_title)
        try:
            post.put()
        except apiproxy_errors.OverQuotaError, message:
            logging.error(message)
            models.cleanOldPosts()
            mail.send_mail(sender="ipsmth@googleappengine.com",
              to="Demiao Lin <ldmiao@gmail.com>",
              subject="It seems that ipsmth had a OverQuotaError",
              body='''
                Dear Demiao:
                
                Your http://ipsmth.appspot.com just had a OverQuotaError:
                --------------------------------
                '''
                + message +
                '''
                --------------------------------
                
                Please check it if you have time.
                
                From: ipsmth@googleappengine.com''')

    config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", getUser()).get()
    #logging.info(config)
    
    return post.post_id, post.thread_id, post.title, post.toHTML(config)